<?php
use \Roboframe\ActiveRecord\Model;
class Role extends Model {
  private $user_ids = null;
  private $permission_ids = null;
  
  static $has_many = array(
    array('user_roles')
   ,array('role_permissions')
   ,array('users', 'through' => 'user_roles')
   ,array('permissions', 'through' => 'role_permissions') 
  );
  
  static $validates_presence_of = array(
    array('name')
  );
  
  static $validates_uniqueness_of = array(
    array('name')
  );
  
  static $setters = array('user_ids', 'permission_ids');
  
  public function set_user_ids(array $user_ids) {
    $this->user_ids = $user_ids;
    /*
    // Remove unchecked roles
    UserRole::delete_all_by_role_id($this->id);
    foreach($user_ids as $user_id) {
      if(!UserRole::find_by_user_id_and_role_id($user_id, $this->id)) {
        if($user_id) {
          $ur = new UserRole();
          $ur->user_id = $user_id;
          $ur->role_id = $this->id;
          if(!$ur->save()) {
            $this->errors->add('user_ids', "Could not add User [{$user_id}] to Role!");
          }
        }
      }
    }
    */
  }
  
  public function set_permission_ids(array $permission_ids) {
    $this->permission_ids = $permission_ids;
  }  

  public function after_save() {
    return ($this->update_users() && $this->update_permissions());
  }
  
  protected function update_users() {
    $failed_user_ids = array();
    if($this->user_ids) {
      UserRole::delete_all_by_role_id($this->id);
      foreach($this->user_ids as $user_id) {
        if(!UserRole::find_by_user_id_and_role_id($user_id, $this->id)) {
          if($user_id) {
            $ur = new UserRole();
            $ur->user_id = $user_id;
            $ur->role_id = $this->id;
            if(!$ur->save()) {
              $failed_user_ids[] = $user_id;
            }
          }
        }
      }
    }
    if(count($failed_user_ids) > 0) {
      $this->errors->add('user_ids', "Could not add Users [".join(', ', $failed_user_ids)."]");
      return false;
    }
    return true;
  }
  
  protected function update_permissions() {
    $failed_permission_ids = array();
    if($this->permission_ids) {
      RolePermission::delete_all_by_role_id($this->id);
      $failed_permission_ids = array();
      foreach($this->permission_ids as $permission_id) {
        if(!RolePermission::find_by_permission_id_and_role_id($permission_id, $this->id)) {
          if($permission_id) {
            $rp = new RolePermission();
            $rp->permission_id = $permission_id;
            $rp->role_id = $this->id;
            if(!$rp->save()) {
              $failed_permission_ids[] = $permission_id;
            }
          }
        }
      }
    }
    if(count($failed_permission_ids) > 0) {
      $this->errors->add('permission_ids', "Could not add Permissions [".join(', ', $failed_permission_ids)."]");
      return false;
    }
    return true;
  }
}